package com.sy.easycms.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.sy.framework.util.EncryptUtil;

public class Admin {

	public Admin() {
	} 
	
	/**
	 * 生成默认XML
	 * @return
	 */
	public boolean initXml() throws DocumentException , IOException
	{
		String path = this.getClass().getResource("/").getPath()+"/admin.xml";
		File file = new File(path);
		if(!file.exists())
		{
			Document doc = DocumentHelper.parseText("<root></root>");
			Element ele = doc.getRootElement().addElement("admin");
			ele.addElement("nickname").setText("Cacti");
			String originalpwd = EncryptUtil.MD5Encode("admin888");
			ele.addElement("password").setText(originalpwd);
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			XMLWriter writer = new XMLWriter(new FileWriter(path),format);
			writer.write(doc);
			writer.flush();
			return true;
		}else
		{
			//文件已存在
			return true;
		}
	}
	
	public boolean changePwd(String old,String npw)
	{
		return true;
	}
	
	public boolean adminLogin(String password) throws IOException , DocumentException
	{
		String path = this.getClass().getResource("/").getPath()+"/admin.xml";
		File file = new File(path);
		if(!file.exists())
		{
			try{
				initXml();
			}catch(IOException e)
			{
				throw new IOException("初始化管理员xml文件失败!");
			}catch(DocumentException e)
			{
				throw new DocumentException("解析管理员xml文件失败!");
			}
			if(password.equals(EncryptUtil.MD5Encode("admin888")))
			{
				return true;
			}
		}else{
			SAXReader reader = new SAXReader();
			Document doc = reader.read(new File(path));
			Element ele = doc.getRootElement();
			Element foo;
			for(Iterator i = ele.elementIterator();i.hasNext();)
			{
				foo = (Element)i.next();
				if(EncryptUtil.MD5Encode(password).equals(foo.elementText("password")))
				{
					System.out.println(foo.elementText("password"));
					return true;
				}
			}
		}
		return true;
	}
}
